#############################################
# Wordpress Connector and Offline Publisher
# 
# author: andreas del galdo
# mail:   andreas.delgaldo@gmx.net
#
#############################################

import sys, os, platform
import wcConnector

def parseConfig(line):
	key = line[0:line.find("=")]
	key = key.strip()

	value = line[line.find("=")+1:]
	value = value.strip()

	return(key,value)

def main():
	#open config file
	if (platform.system().find('Linux') != -1):
		configHandler = open('/etc/wcaop/WCaOP.conf','r')
	else:
		configHandler = open('WCaOP.conf','r')

	#creating config dictionary
	config = dict()
	for line in configHandler.readlines():
		(key,value) = parseConfig(line)
		config[key] = value
	
	#closes the config file
	configHandler.close()
	
	#open a wordpress connection
	wpHandler = wcConnector.openWordpress(config['name'], config['url'], config['user'], config['pass'])
	
	if (wpHandler != False):
		post = dict()
		if (len(sys.argv) > 1):
			#read the textfile with the content and the title
			contentFile = open(sys.argv[2],'r')
			post['title'] = sys.argv[1]
			post['description'] = contentFile.read()
			
			contentFile.close()
			wcConnector.publishPost(wpHandler,post['title'],post['description'],None)
		else:
			#get and print categories
			categories = wcConnector.getCategories(wpHandler)
			for i in range(len(categories)):
				sys.stdout.write("%s, " % categories[i])
			sys.stdout.write("\r\n===============================================\r\n\n")

			#ask for entry date
			post['title'] = raw_input('Title for Entry:\t')
			contentFile = open(raw_input('File including Content:\t'),'r')
			post['description'] = contentFile.read()
			post['category'] = raw_input('Category for Entry:\t')
			
			#post to blog system
			wcConnector.publishPost(wpHandler,post['title'],post['description'],post['category'])


####### __main__ call ####### 
if __name__ == '__main__':
	try:
		main()
	except:
		print "\r\n\nError in running WCaOP\r\n"
